package br.com.hs.nfe.common.validation;

import br.com.hs.nfe.common.app.AppConfig;
import br.com.hs.nfe.common.enumeration.SituacaoNFeEnum;
import br.com.hs.nfe.common.exception.HSCommonException;
import br.com.hs.nfe.common.to.NotaFiscalTO;
import br.com.hs.nfe.common.util.HSConstants;
import br.com.hs.nfe.common.validation.exception.HSValidationException;
import br.inf.portalfiscal.nfe.NFeDocument;
import java.util.List;

/**
 * Classe de validação da NF-e.
 * @author Ranlive Hrysyk
 */
public class NotaFiscalValidation {

    private static NotaFiscalValidation notaFiscalValidation;

    /**
     * Construtor privado para impedir o instânciamento desta classe de outro modo.
     */
    private NotaFiscalValidation() {
    }

    /**
     * Obtém a instância da classe.
     */
    public static NotaFiscalValidation getInstance() {
        if (notaFiscalValidation == null) {
            notaFiscalValidation = new NotaFiscalValidation();
        }
        return notaFiscalValidation;
    }

    /**
     * Valida o máximo de bytes da NF-e sem assinatura.
     */
    public boolean validarMaximoBytes(String docXmlString) {
        int tamanhoMaximoPermitido = HSConstants.MAXIMO_BYTES_NOTA_FISCAL - HSConstants.NUMERO_BYTES_ASSINATURA_NOTA_FISCAL;
        return (docXmlString == null) || (docXmlString.getBytes().length <= tamanhoMaximoPermitido);
    }

    /**
     * Valida as regras de negócio na NF-e.
     */
    public void validarDocumentoXML(NotaFiscalTO notaFiscalTO, NFeDocument doc) throws HSValidationException {
        new ValidadorNotaFiscal().validarNotaFiscalTO(notaFiscalTO, doc);
    }

    /**
     * Valida o schema XML da NF-e.
     */
    public void executarValidacaoXMLBeans(NotaFiscalTO notaFiscalTO, NFeDocument doc) throws HSValidationException {
        if (!doc.validate()) {
            try {
                List<String> validationErrors = HSSchemaValidator.getInstance().validate(HSSchemaTypeEnum.nfe, AppConfig.getInstance().getVersaoSchema(), doc.xmlText());
                for (String error : validationErrors) {
                    if ((notaFiscalTO.getSituacao() == null) || (SituacaoNFeEnum.EM_DIGITACAO.equals(notaFiscalTO.getSituacao())) || (SituacaoNFeEnum.VALIDADA.equals(notaFiscalTO.getSituacao()))) {
                        if (!error.contains(HSConstants.XML_TAG_ASSINATURA)) {
                            notaFiscalTO.addValidationError(error);
                        }
                    } else {
                        notaFiscalTO.addValidationError(error);
                    }
                }
            } catch (HSCommonException ex) {
                throw new HSValidationException(ex);
            }
        }
    }
}
